#! /usr/bin/python

#Script to monitor a web sites response times and alert if sowdown is seen
#developed on Linux Mint 13/Ubuntu 12.04, Windows support coming

#Changelog
# - more error handling (to catch missing http://)
#05.06.2012 - v 1.01 - Added retry capability to the intial connectivity test.
#05.06.2012 - v 1.0 - initial release, more a POC



import time, urllib, urllib2, sys, optparse, signal, os

print "web-check.py v1..01"
usageString = """Usage: %prog {URL}
Example: web-check.py http://www.google.com
"""
parser = optparse.OptionParser(usage=usageString, version="%prog v1.01")
(opts, args) = parser.parse_args()

if len(args) < 1:
  parser.error("URL is required!")

host = args[0]

# Catch ctrl+c, very basic right now
Original_Except_Hook = sys.excepthook
def New_Except_Hook(type, value, traceback):
	if type == KeyboardInterrupt:
		exit("\nCTRL+C detected, Exiting.")
	else:
		Original_Except_Hook(type, value, traceback)
sys.excepthook = New_Except_Hook

# Define the functions required

def test_URL_func(retry=0):
	try:
		urllib2.urlopen(host)
	except urllib2.URLError, error:
		retry +=1
		print "Cannot connect to " + host + ". Retrying again in 2 seconds. Retry:" + str(retry)
		time.sleep(2)
		if retry < 3:
			test_URL_func(retry)
		else:
			print "Cannot connect. Error: " + str(error.reason)
			sys.exit()
	except ValueError as error:
		print "Error - '" + str(error) + "'. Did you forget the protocol? e.g. 'http://'"
		sys.exit()
		

def timed_page_request_func():
	page_load = ''
	timed_request = urllib2.Request(host)
	timed_response = urllib2.urlopen(timed_request)
	load = True
	while load:
		load = 	timed_response.read(1024)
		page_load += load
	timed_response.close()

# confirm connectivity to site
print "Sending first request....."
time.sleep(0.5)

test_URL_func(retry=0)

# Check for redirects and ask user if so			
response = urllib2.urlopen(host)			
if response.geturl() == host:
	print "Site appears up"
	time.sleep(0.5)
elif response.geturl() != host:
	redirected_host = response.geturl()
	redirect_question = raw_input("Redirect detected to '" + redirected_host + "'. Do you want to follow it? [Y/N]")
	if redirect_question == 'Y':
		host = response.geturl()
	else:
		print "OK, exiting"
		sys.exit()

#Calculate the average response time for the site

print "Calculating average response time for complete load of the requested URL based on 10 requests......"

initialresponselist = []
x = 1

while x <= 10:
	initial_start_time = time.time()
	timed_page_request_func()
	initial_end_time = time.time()
	initial_response_time = (initial_end_time - initial_start_time)
	print "Request " + str(x) + ": " + str(initial_response_time)
	initialresponselist.append (initial_response_time)
	x = x + 1

average_response_time = sum(initialresponselist) / 10
print "Initial average response time is: " + str(average_response_time) + " seconds"

# Confirm user wants to monitor the site

Monitor_site_question = raw_input("Continue to monitor '" + host + "'? [Y/N]")
if Monitor_site_question == 'Y':
	print "Monitoring response times of '" + host + "'"
else:
	print "OK, exiting"
	sys.exit()

# Monitor the site response times	
	
percentage_difference = 0
z = 1

while z < 2:
	if percentage_difference < 100:
		monitor_start_time = time.time()
		timed_page_request_func()
		monitor_end_time = time.time()
		monitor_response_time = (monitor_end_time - monitor_start_time)
		percentage_difference = round((float(1 * (monitor_response_time - average_response_time) / average_response_time) * 100),2)
		print "Response time: " + str(monitor_response_time) + ". " + str(percentage_difference) + "% difference"
	elif percentage_difference >= 100:
		print "Site appears to be slowing down \a"
		os.system("aplay beep-07.wav > /dev/null 2>&1") # play alarm and pipe stdout to null
		percentage_difference = 0

print "Exiting"
